<template>
  <div class="page-container">
    <div class="in-container">
      <FinancialSearchFrom
        :query="query"
        @reset="reset"
        @saveData="saveData"
        :tableData="tableData.data"
        ref="financialSearchFromRef"
        @clearTableData="clearTableData"
        :totalCount="totalCount"
        :exchangeRateData="exchangeRateData"
      ></FinancialSearchFrom>
      <div class="btn-box">
        <el-button type="primary" @click="openPayableFee">审核费用</el-button>
        <el-button type="primary" @click="deleWriteOff"> 删除销账</el-button>
      </div>
      <AppPageTable
        stripe
        :data="tableData.data"
        :autostyle="'height: calc(100% - 304px);'"
        :isPagination="true"
        :option="tableData.option"
        @cellClick="cellClick"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          width="60"
          label="序号"
          type="index"
          fixed="left"
          align="center"
        >
        </el-table-column>
        <el-table-column label="收/付" width="115" align="center">
          <template #default="scope">
            {{ scope.row.isIncome ? '收款' : '付款' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="doccode"
          width="115"
          label="业务编号"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="blNo" width="115" label="提单号" align="center">
        </el-table-column>
        <el-table-column
          prop="feeName"
          align="center"
          label="费用类型"
          width="115"
        >
        </el-table-column>
        <el-table-column prop="currency" align="center" label="币种" width="80">
        </el-table-column>
        <el-table-column
          prop="totalmoney"
          align="center"
          label="金额"
          width="115"
        >
        </el-table-column>
        <el-table-column
          prop="verificationMoney"
          align="center"
          label="销账金额"
          width="115"
        >
          <template #default="scope">
            <div
              v-if="
                scope.row.index === rowIndex && scope.column.index === colIndex
              "
            >
              <el-input
                v-model="scope.row.verificationMoney"
                :min="0"
                :max="scope.row.totalmoney"
                size="small"
                :precision="2"
                ref="verificationMoneyRef"
                @change="handleRowChange(scope.row, 'verificationMoney')"
                @blur="loseFocusInput"
                @input="
                  scope.row.verificationMoney = validateNumber(
                    scope.row.verificationMoney
                  )
                "
              >
              </el-input>
            </div>
            <span v-else>{{ scope.row.verificationMoney }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="getUnVerificationMoney"
          align="center"
          label="未销金额"
          width="115"
        >
        </el-table-column>
        <el-table-column
          prop="createTime"
          align="center"
          label="销账日期"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="createBy"
          align="center"
          label="销账人"
          width="115"
        >
        </el-table-column>
        <el-table-column
          prop="invoiceCode"
          align="center"
          label="发票号"
          width="115"
        >
        </el-table-column>
        <el-table-column
          prop="invoiceDate"
          align="center"
          label="发票日期"
          width="115"
        >
          <template #default="scope">
            {{
              scope.row.invoiceDate
                ? scope.row.invoiceDate.substring(0, 10)
                : scope.row.invoiceDate
            }}
          </template>
        </el-table-column>
        <el-table-column prop="feeMemo" align="center" label="备注">
        </el-table-column>
      </AppPageTable>
    </div>
    <FinacialTotal
      style="margin-top: 4px"
      :totalCount="totalCount"
      :isFeeCount="true"
      :doctype="query.doctype"
    ></FinacialTotal>
    <FinacialPayableFee
      ref="payableFeeRef"
      @selectOver="selectOver"
      :doctype="query.doctype"
    ></FinacialPayableFee>
  </div>
</template>

<script>
import { defineComponent } from 'vue'
import FinancialSearchFrom from './FinancialSearchFrom.vue'
import FinacialTotal from './FinacialTotal.vue'
import FinacialPayableFee from './FinacialPayableFee.vue'
import AppPageTable, { useTableOption } from '@/components/AppPageTable2'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatNum } from '@/utils/format.ts'
import { validateNumber } from '@/utils/validate.js'
import bus from '@/utils/vueBus'
export default defineComponent({
  components: {
    AppPageTable,
    FinancialSearchFrom,
    FinacialTotal,
    FinacialPayableFee
  },
  props: {
    doctype: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      // 查询条件
      query: {
        // 银行卡号
        bankAccount: '',
        // 银行账号名称
        bankAccountName: '',
        // 银行名称
        bankName: '',
        // 可销账金额
        canverificationMoney: '',
        // 审核状态 0草稿 1提交审核  2审核通过  -1驳回
        checkStatus: 0,
        // 付款币种
        currency: '',
        // 付款单号
        doccode: '',
        // 付款日期
        docdate: dayjs().format('YYYY-MM-DD'),
        // 费用单号
        balanceDoccode: '',
        // 收付类型:1 收款,0付款
        doctype: this.doctype,
        // 结算对象代码（左）
        entCode: '',
        // 结算对象名称（右）
        entFullname: '',
        // 结算对象Id
        entId: '',
        //汇率
        exchangeRate: '',
        // 销账币种
        feeCurrency: '',
        // 摘要
        memo: '',
        // 业务员Id
        salesId: '',
        // 业务员名称
        salesName: '',
        // 付款金额
        sumtotalmoney: '',
        // 已销金额
        sumverificationMoney: '',
        // 未销金额
        unVerificationMoney: '',
        //  审核人名称
        checkBy: '',
        // 录入人
        updateBy: this.$store.getters['auth/getUser'].nickName,
        // 录入日期
        updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
      },
      //表格数据
      tableData: {
        data: [],
        option: useTableOption()
      },
      // 合计金额
      totalCount: {
        // 应付合计
        sumtotalmoney: 0,
        // 已销金额
        sumverificationMoney: 0,
        // 未销金额
        unVerificationMoney: 0
      },
      colIndex: -1,
      rowIndex: -1,
      exchangeRateData: []
    }
  },
  methods: {
    validateNumber,
    // 重置
    reset() {
      this.query = {
        // 银行卡号
        bankAccount: '',
        // 银行账号名称
        bankAccountName: '',
        // 银行名称
        bankName: '',
        // 可销账金额
        canverificationMoney: '',
        // 审核状态 0草稿 1提交审核  2审核通过  -1驳回
        checkStatus: 0,
        // 付款币种
        currency: '',
        // 付款单号
        doccode: '',
        // 付款日期
        docdate: dayjs().format('YYYY-MM-DD'),
        // 费用单号
        balanceDoccode: '',
        // 收付类型:1 收款,0付款
        doctype: this.doctype,
        // 结算对象代码（左）
        entCode: '',
        // 结算对象名称（右）
        entFullname: '',
        // 结算对象Id
        entId: '',
        //汇率
        exchangeRate: '',
        // 销账币种
        feeCurrency: '',
        // 摘要
        memo: '',
        // 业务员Id
        salesId: '',
        // 业务员名称
        salesName: '',
        // 付款金额
        sumtotalmoney: '',
        // 已销金额
        sumverificationMoney: '',
        // 未销金额
        unVerificationMoney: '',
        //  审核人名称
        checkBy: '',
        // 录入人
        updateBy: this.$store.getters['auth/getUser'].nickName,
        // 录入日期
        updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
      }
    },

    // 已销金额同步更新
    handleRowChange(row) {
      // 当前数据还存在未销的金额，输入的金额不能高于该值
      let maxMoney = row.getUnVerificationMoney + row.getVerificationMoney
      row.getVerificationMoney = formatNum(
        row.verificationMoney,
        2,
        0,
        maxMoney
      )
      row.verificationMoney = row.verificationMoney
        ? Number(row.verificationMoney)
        : 0
      if (row.verificationMoney >= parseFloat(maxMoney)) {
        row.verificationMoney = parseFloat(maxMoney)
      }
      row.getUnVerificationMoney = Math.trunc(
        parseFloat(row.x_verificationMoney) +
          parseFloat(row.x_unVerificationMoney) -
          parseFloat(row.verificationMoney)
      )
      // 原来的逻辑
      // row.getVerificationMoney = formatNum(
      //   row.verificationMoney,
      //   2,
      //   0,
      //   row.totalmoney
      // )
      // row.verificationMoney = row.verificationMoney
      //   ? Number(row.verificationMoney)
      //   : 0
      // if (row.verificationMoney >= parseFloat(row.totalmoney)) {
      //   row.verificationMoney = parseFloat(row.totalmoney)
      // }
      // row.getUnVerificationMoney = Math.trunc(
      //   parseFloat(row.x_verificationMoney) +
      //     parseFloat(row.x_unVerificationMoney) -
      //     parseFloat(row.verificationMoney)
      // )
      this.refreshCount([], 'searchChange')
    },

    // 输入框失去焦点
    loseFocusInput() {
      this.colIndex = -1
      this.rowIndex = -1
    },

    // 单元格点击
    cellClick({ row, column }) {
      this.colIndex = column.index
      this.rowIndex = row.index
      this.$nextTick(() => {
        this.$refs.verificationMoneyRef.focus()
      })
    },

    // 打开应付/应收费用弹窗
    openPayableFee() {
      const sonVal = this.$refs.financialSearchFromRef.query
      // 查询条件需要先输入销账币种和结算对象
      if (sonVal.entId === '' || sonVal.feeCurrency === '') {
        this.$message.warning('请输入结算对象名称和销账币种')
        return
      }
      this.$refs.payableFeeRef.open(
        sonVal.feeCurrency,
        sonVal.entId,
        sonVal.sumtotalmoney,
        0
      )
    },
    // 删除销账
    async deleWriteOff() {
      if (!this.tableData.option.selected.length) {
        this.$message.warning('请选择数据')
        return
      }
      ElMessageBox.confirm('是否确定执行删除操作？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let newArray = []
        this.tableData.data.forEach((t) => {
          if (!this.tableData.option.selected.find((item) => t == item)) {
            newArray.push(t)
          }
        })

        this.tableData.data = newArray

        this.refreshCount([], 'searchChange')
      })
    },
    // 选中的表格数据
    selectOver(selectTableData) {
      let CpoySelectTableData = JSON.parse(JSON.stringify(selectTableData))
      let newArray = []
      CpoySelectTableData.forEach((t) => {
        if (
          !this.tableData.data.find((item) => t.workfeeId == item.workfeeId)
        ) {
          newArray.push(t)
        }
      })
      CpoySelectTableData = newArray
      CpoySelectTableData.forEach((item) => {
        item.getVerificationMoney = item.getUnVerificationMoney
        item.verificationMoney = item.getUnVerificationMoney
        item.x_verificationMoney = item.verificationMoney
        item.xverificationMoney = Math.trunc(
          item.totalmoney - item.getUnVerificationMoney
        )
        item.getUnVerificationMoney = Math.trunc(
          item.totalmoney - item.verificationMoney - item.xverificationMoney
        )
        item.x_unVerificationMoney = item.getUnVerificationMoney
      })
      this.refreshCount(CpoySelectTableData, 'searchChange')
    },

    // 重置表格数据
    clearTableData() {
      this.tableData.data = []
      this.tableData.option.selected = []
      // this.$refs.financialSearchFromRef.query.canverificationMoney = "0";
      // this.$refs.financialSearchFromRef.query.sumverificationMoney = "0";
      // this.$refs.financialSearchFromRef.query.unVerificationMoney = "0";
      //this.refreshCount([], "searchChange");
    },

    // changeType:isSearchChange第二参数有值时，需要修改搜索条件里的已销金额;addTableData:当选择销账数据时，外部列表已存在数据时,settingSumtotalmoney:从应收应付对账跳转
    refreshCount(selectTableData, changeType, settingSumtotalmoney) {
      this.totalCount = {
        // 应付合计
        sumtotalmoney: 0,
        // 已销金额
        sumverificationMoney: 0,
        // 未销金额
        unVerificationMoney: 0
      }
      this.tableData.data = this.mergeAndRemoveDuplicates(
        JSON.parse(JSON.stringify(selectTableData)),
        JSON.parse(JSON.stringify(this.tableData.data))
      )
      for (const iterator of this.tableData.data) {
        const flag = iterator.isIncome == this.query.doctype ? 1 : -1
        this.totalCount.sumtotalmoney += iterator.getTotalmoney
          ? parseFloat(iterator.getTotalmoney) * flag
          : 0
        this.totalCount.sumverificationMoney += iterator.getVerificationMoney
          ? parseFloat(iterator.getVerificationMoney) * flag
          : 0
        this.totalCount.unVerificationMoney += iterator.getUnVerificationMoney
          ? parseFloat(iterator.getUnVerificationMoney) * flag
          : 0
      }
      this.$refs.financialSearchFromRef.query.exchangeRate =
        this.tableData.data[0].exchangeRate
      // this.$refs.financialSearchFromRef.query.checkStatus =
      //   this.tableData.data[0].checkStatus;
      this.$refs.financialSearchFromRef.query.createBy =
        this.tableData.data[0].createBy
      this.$refs.financialSearchFromRef.query.createTime = dayjs().format(
        'YYYY-MM-DD HH:mm:ss'
      )

      var a =
        this.exchangeRateData[this.query.feeCurrency + '' + this.query.doctype]
      var b =
        this.exchangeRateData[this.query.currency + '' + this.query.doctype]

      let num = (b / a) * this.$refs.financialSearchFromRef.query.sumtotalmoney

      if (num >= this.totalCount.sumverificationMoney) {
        this.$refs.financialSearchFromRef.query.canverificationMoney = num
      } else {
        this.$refs.financialSearchFromRef.query.canverificationMoney =
          this.totalCount.sumverificationMoney
      }

      if (this.$refs.financialSearchFromRef.query.canverificationMoney < 0) {
        this.$refs.financialSearchFromRef.query.canverificationMoney = 0
      }

      this.$refs.financialSearchFromRef.query.sumverificationMoney =
        this.totalCount.sumverificationMoney
      this.$refs.financialSearchFromRef.query.unVerificationMoney = Math.trunc(
        this.totalCount.sumtotalmoney - this.totalCount.sumverificationMoney
      )
      // this.$refs.financialSearchFromRef.query.checkStatus = 0;
      //   if (changeType) {
      //     let sumverificationMoney = Math.trunc(
      //       this.totalCount.sumverificationMoney
      //     )
      //       ? Math.trunc(this.totalCount.sumverificationMoney)
      //       : 0;
      //     this.query.sumverificationMoney = sumverificationMoney;
      //   }
      //   if (settingSumtotalmoney) {
      //     this.query.sumtotalmoney = this.query.sumverificationMoney;
      //   }
      //   this.$refs.financialSearchFromRef.canverificatioChange(
      //     Math.trunc(this.totalCount.sumverificationMoney)
      //   );
    },

    // 合并数组并去重
    mergeAndRemoveDuplicates(arr1, arr2) {
      let hash = {}
      // 合并两个数组
      let newArr = arr1.concat(arr2)
      const mergedArr = newArr.reduce((item, next) => {
        hash[next.workfeeId]
          ? ''
          : (hash[next.workfeeId] = true && item.push(next))
        return item
      }, [])
      return mergedArr
    },

    // 选择的费用数据重新组合 data = this.tableData
    resetFeeList(data) {
      let feeList = []
      for (const iterator of data) {
        let obj = {}
        obj = {
          docId: iterator.docId,
          workfeeId: iterator.workfeeId,
          verificationMoney: iterator.verificationMoney,
          feeMemo: iterator.feeMemo,
          isDeleted: iterator.isDeleted,
          isIncome: iterator.isIncome,
          doccode: iterator.doccode,
          blNo: iterator.blNo,
          feeName: iterator.feeName,
          currency: iterator.currency,
          totalmoney: iterator.totalmoney,
          invoiceCode: iterator.invoiceCode,
          invoiceDate: iterator.invoiceDate,
          balanceDoccode: iterator.balanceDoccode,
          getUnVerificationMoney: iterator.getUnVerificationMoney,
          getTotalmoney: iterator.getTotalmoney,
          getVerificationMoney: iterator.getVerificationMoney
        }
        if (iterator.id) {
          obj['id'] = iterator.id
        }
        feeList.push(obj)
      }
      return feeList
    },

    // 当前页面应收应付下的币种汇率
    async getExchangeRateData() {
      let res = await this.$http.get('/api/base/exchangerate/query', {
        IsIncome: this.query.doctype
      })
      res.content.map((item) => {
        this.exchangeRateData[item.currency + item.isIncome] = item.exchangeRate
      })
      // 应收或应付对账页面跳转
      if (this.$route.query.currency) {
        this.query.currency = this.$route.query.currency
        this.query.feeCurrency = this.$route.query.currency
        this.query.exchangeRate =
          this.exchangeRateData[this.query.feeCurrency + this.query.doctype]
        let selectedIds = JSON.parse(this.$route.query.selectedIds)
          ? JSON.parse(this.$route.query.selectedIds)
          : []
        if (selectedIds instanceof String) {
          selectedIds = [selectedIds]
        }
        this.$http
          .post(`/api/docBalance/getFeeListByBalanceIds?feeStatus=0`, {
            idArray: selectedIds
          })
          .then((res) => {
            const tmp = res[0]
            this.query.entCode = tmp.entCode
            this.query.entFullname = tmp.entFullname
            this.query.entId = tmp.entId
            // this.$refs.financialSearchFromRef.getBusDetail(tmp.entCode);  //根据endtCode查询无法获取到对应的数据
            this.$refs.financialSearchFromRef.getCurrentData(
              this.$route.query.currency
            )
            this.$refs.financialSearchFromRef.settlementList = [
              {
                label: this.query.entCode,
                value: this.query.entId
              }
            ]
            const rows = res.filter(
              (item) => item.currency == this.$route.query.currency
            )
            if (rows.length > 0) {
              let CpoySelectTableData = JSON.parse(JSON.stringify(rows))
              this.tableData.data = CpoySelectTableData
              CpoySelectTableData.forEach((item) => {
                item.getVerificationMoney = item.getUnVerificationMoney
                item.verificationMoney = item.getUnVerificationMoney
                item.x_verificationMoney = item.verificationMoney
                item.xverificationMoney = Math.trunc(
                  item.totalmoney - item.getUnVerificationMoney
                )
                item.getUnVerificationMoney = Math.trunc(
                  item.totalmoney -
                    item.verificationMoney -
                    item.xverificationMoney
                )
                item.x_unVerificationMoney = item.getUnVerificationMoney
              })
              //this.refreshCount(CpoySelectTableData, "searchChange", "settingSumtotalmoney");
            }
          })
      }
    },
    // 保存==
    async saveData(query) {
      query.canverificationMoney = query.canverificationMoney
        ? parseFloat(query.canverificationMoney)
        : 0
      query.sumtotalmoney = query.sumtotalmoney
        ? parseFloat(query.sumtotalmoney)
        : 0
      query.exchangeRate = query.exchangeRate
        ? parseFloat(query.exchangeRate)
        : 0
      query.sumverificationMoney = query.sumverificationMoney
        ? parseFloat(query.sumverificationMoney)
        : 0
      query.unVerificationMoney = query.unVerificationMoney
        ? parseFloat(query.unVerificationMoney)
        : 0
      if (this.totalCount.sumverificationMoney < 0) {
        this.$message.error(
          `销账金额为负数，请做${query.doctype ? '收款' : '付款'}管理！`
        )
        return
      }
      if (this.totalCount.sumverificationMoney > query.canverificationMoney) {
        this.$message.error(
          `合计销账金额不能超过${query.doctype ? '收款' : '付款'}可核销金额！`
        )
        return
      }
      let reqData = {
        docCashItemList: this.resetFeeList(this.tableData.data),
        ...query,
        id: this.$route.query.id ? this.$route.query.id : 0
      }
      if (query.isDZ) {
        reqData.docCashItemList.forEach((item) => {
          item.workfeeId = item.id
        })
      }
      let res = await this.$http.post('/api/doccash/save', reqData)
      if (res.status) {
        let deatailData = await this.$http.get('/api/doccash/get', {
          id: res.data
        })
        if (deatailData.status) {
          // 跳转对应的收付款页面
          if (!(this.isPageJump && this.fileUploadVisible)) {
            if (this.query.doctype == 1) {
              this.$router.openTab({
                name: 'cashDetail',
                query: {
                  id: res.data,
                  title: '收款详情' + deatailData.data.doccode,
                  iscash: true
                }
              })
            } else {
              this.$router.openTab({
                name: 'cashOutDetail',
                query: {
                  id: res.data,
                  title: '付款详情' + deatailData.data.doccode,
                  iscash: true
                }
              })
            }
          } else {
            let routeData = {
              path: this.$route.path,
              query: {
                id: res.data,
                title:
                  this.query.doctype == 1
                    ? '收款详情' + deatailData.data.doccode
                    : '付款详情' + deatailData.data.doccode,
                iscash: this.$route.query.iscash
              }
            }
            this.$router.closeAndRefreshTab(routeData)
            this.$emit('payDetailsSave', deatailData)
          }
          ElMessage.success('保存成功')
        } else {
          ElMessage.warning(deatailData.message)
        }
      } else {
        ElMessage.warning(res.message)
      }
    }
  },
  watch: {
    //主要用来监听里面的getVerificationMoney值的变化，实时发送给FinancialSearchFrom组件
    'tableData.data'(newval) {
      if (newval.length) {
        if (newval.length >= 2) {
          let price = newval.reduce(
            (sum, e) => sum + Number(e.getVerificationMoney || 0),
            0
          )
          bus.emit('getVerificationMoney', price)
        } else {
          bus.emit('getVerificationMoney', newval[0].getVerificationMoney)
        }
      }
    }
  },

  mounted() {
    bus.emit('doctype', this.query.doctype)
    this.getExchangeRateData()
  }
})
</script>

<style lang="scss" scoped>
.btn-box {
  margin-bottom: 8px;
}
</style>
